package com.framework.seedkit.http.volley;

import android.text.TextUtils;

import com.framework.seedkit.base.BaseApplication;
import com.framework.seedkit.utils.LOG;
import com.framework.seedkit.utils.OSUtil;
import com.framework.seedkit.utils.cacheUtil.SharedPref;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

public class HeadUtil {

	public static JSONObject getHeadJson(String token) {
		JSONObject headJson = new JSONObject();
		try {
			headJson.put("Token", token);
			headJson.put("Version", OSUtil.verName);

			String key_channel = "key_channel_id";
			String channel = SharedPref.getString(BaseApplication.getInstance(), key_channel);
			if (TextUtils.isEmpty(channel)) {
				channel = SharedPref.getString(BaseApplication.getInstance(), key_channel);
			}
			headJson.put("Channel", channel);

			headJson.put("AppType", "1");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		// Log.e("", "-------------- head json = " + headJson.toString());
		return headJson;
	}

	public static JSONObject getHeadJson() {
		if (TextUtils.isEmpty(BaseApplication.token)) {
			return getHeadJson(SharedPref.getString(BaseApplication.getInstance(), "token"));
		}
		return getHeadJson(BaseApplication.token);
	}

	public static JSONObject getJsonByParamter(Map<String, Object> parameters) {

		JSONObject json = new JSONObject();

		try {
			//put head section
			json.put("Head", HeadUtil.getHeadJson());

			//put content section
			JSONObject content = new JSONObject();

			if (parameters != null) {
				for (Map.Entry<String, Object> pair : parameters.entrySet()) {
					content.put(pair.getKey(), pair.getValue());
				}
			}
			
			json.put("Content", content);
			
			LOG.e("request--->" + json.toString());
			
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return json;
	}
	
	//获取返回的JSONObject Head中的 Ret
	public static int getReturnRet(JSONObject json) {
		if (json == null) {
			return -1;
		}
//		Log.e(tag, "------------ json = " + json.toString());
		return json.optJSONObject("Head").optInt("Ret");
	}

}
